//
//  ZiXunDetailViewController.m
//  JJHW_coreData
// 资讯详情页
//  Created by lizhenqiang on 16/4/9.
//  Copyright © 2016年 HFKJ_LZQ. All rights reserved.
//

#import "ZiXunDetailViewController.h"
#import "ShareHandle.h"
#import "TitleNewsCell.h"
#import "NewsTitleCell.h"
#import "NewsImageCell.h"
#import "NewsWebCell.h"
#import "ADDetailViewController.h"
#import "PhotoBrowser.h"
#define KshareBaseUrl @"http://wechat.m.jjhw.com/news/wechat?id="

@interface ZiXunDetailViewController ()
@property (nonatomic, strong)NSMutableArray *arrayContent; //cell内容
@property (nonatomic, strong)NSMutableArray *arrayHeight;  //cell行高
@property (nonatomic, strong)NSMutableArray *arrayImages;  //图片数组
@property(strong, nonatomic)NSString *shareTitle;//分享出去的标题
@property(strong, nonatomic)NSString *shareContent;
@property(strong, nonatomic)NSString *publishTime;//发布时间
@end

@implementation ZiXunDetailViewController

- (void)viewDidLoad {
    self.titleForNav =@"资讯正文";
    [super viewDidLoad];
    self.arrayContent =[[NSMutableArray alloc] init];
    self.arrayHeight =[[NSMutableArray alloc] init];
    self.tableView.frame =CGRectMake(0, 64, DeviceWidth, DeviceHeight-64);
    self.tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[TitleNewsCell class] forCellReuseIdentifier:@"TitleNewsCell"];
    [self.tableView registerClass:[NewsTitleCell class] forCellReuseIdentifier:@"NewsTitleCell"];
    [self.tableView registerClass:[NewsImageCell class] forCellReuseIdentifier:@"NewsImageCell"];
    [self.tableView registerClass:[NewsWebCell class] forCellReuseIdentifier:@"NewsWebCell"];
//    [self getNewsDetailRequest];
    
    // Do any additional setup after loading the view.
    NavBarItem *rightItem = [[NavBarItem alloc] init];
    rightItem.type = NavBarItemTypeImage;
    rightItem.normalImage = [UIImage imageNamed:@"icon_share"];
    rightItem.selectImage = [UIImage imageNamed:@"icon_share"];
    rightItem.btnFrame = CGRectMake(0, 0, 16, 22);
    
//    self.tableView.estimatedRowHeight = 100;
//    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self setRightNavItemWith:rightItem];
    [self getNewsDetailRequest];
    [self addLabelNoDataToView:self.tableView AndText:@"暂无数据" andFrame:kNoDataLabelFrame];
}
//-(void)getNewsDetailRequest
//{
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:_newsId,@"id", nil];
//    [[CDAPIManager sharedManager] request_newsDetail_WithParams:dic andIsSign:YES andBlock:^(id data,NSError *error){
//        //这个接口调用成功了
//        //需要把这部分数据给保存一下
//    }];
//}

-(void)rightItemClick:(id)sender
{
    [self share];
}
-(void)share
{
    NSString *shareText = [NSString isEmpty: _shareTitle ]?@"鲸鲸海外":_shareTitle;
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",KshareBaseUrl,_newsId];
    UIImage *tempImage;
    if (![NSString isEmpty:_shareImageStr]) {
        tempImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_shareImageStr]]];
    }
    if (tempImage==nil) {
        tempImage = [UIImage imageNamed:@"icon_qq"];//qq分享的图片不能太大
        
    }
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    [shareParams SSDKSetupShareParamsByText:shareText
                                     images:@[tempImage]
                                        url:[NSURL URLWithString:strUrl]
                                      title:shareText
                                       type:SSDKContentTypeAuto];//SSDKContentTypeAuto SSDKContentTypeImage
    
    [shareParams SSDKSetupSinaWeiboShareParamsByText:[NSString stringWithFormat:@"%@ %@",shareText,strUrl] title:shareText image:tempImage url:nil latitude:0 longitude:0 objectID:nil type:SSDKContentTypeAuto];
//    NSArray *iconArray = @[@"icon_wx",@"icon_wxpyq",@"icon_qq",@"icon_qqkj",@"icon_xlwb"];
//    NSArray *titleArray = @[@"微信好友",@"朋友圈",@"QQ",@"QQ空间",@"新浪微博"];
//    //    NSArray *plateArray = @[@(SSDKPlatformSubTypeWechatSession),@(SSDKPlatformSubTypeWechatTimeline),@(SSDKPlatformSubTypeQQFriend),@(SSDKPlatformSubTypeQZone),@(SSDKPlatformTypeSinaWeibo)];
//    NSArray *plateArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:22],[NSNumber numberWithInt:23],[NSNumber numberWithInt:24],[NSNumber numberWithInt:6],[NSNumber numberWithInt:1], nil];
//    
//    NSMutableArray *activePlatforms = [ShareHandle getSharePlateList:self.view andIconArray:iconArray andTitleArray:titleArray andPlateArray:plateArray andPrama:shareParams];
    
    NSMutableArray *activePlatforms = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithInt:22],[NSNumber numberWithInt:23],[NSNumber numberWithInt:24],[NSNumber numberWithInt:6],[NSNumber numberWithInt:1], nil];
    //添加一个自定义的平台（非必要）
    SSUIShareActionSheetCustomItem *item = [SSUIShareActionSheetCustomItem itemWithIcon:[UIImage imageNamed:@"lzq_link"] label:@"复制" onClick:^{//自定义item被点击的处理逻辑  icon_lj
        CDLog(@"=== 自定义item被点击 ===");
//        [MBProgressHUD showMessage:@"已复制"];//停不下来
        [MBProgressHUD showSuccess:@"已复制" toView:self.view];
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        [pasteboard setURL:[NSURL URLWithString:strUrl]];
    }];
    
    [activePlatforms addObject:item];
    
    
    
    [ShareSDK showShareActionSheet:self.view items:activePlatforms shareParams:shareParams onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType,NSDictionary *userData,SSDKContentEntity *contentEntity,NSError *error,BOOL end){
        /**
         *  分享状态变更
         *
         *  @param state         返回状态
         *  @param platformType  平台类型
         *  @param userData      用户数据
         *  @param contentEntity 分享内容实体
         *  @param error         错误信息
         *  @param end           是否已经结束本次分享标识
         */
        switch (state) {
            case SSDKResponseStateBegin: {
                CDLog(@"开始分享");
                break;
            }
            case SSDKResponseStateSuccess: {
                [MBProgressHUD showSuccess:@"分享成功" toView:self.view];
                break;
            }
            case SSDKResponseStateFail: {
                [MBProgressHUD showError:@"分享失败" toView:self.view];
                break;
            }
            case SSDKResponseStateCancel: {
                //                [self.view makeToast:@"分享已取消" duration:1.0 position:@"top"];
                CDLog(@"分享已取消");
                break;
            }
        }
        
    }];
    
}

#pragma mark - UITableView DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arrayContent.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CDLog(@"cell的高度=%f",[self.arrayHeight[indexPath.row] floatValue]);
    return [self.arrayHeight[indexPath.row] floatValue];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row ==0) {
        TitleNewsCell *cell =[tableView dequeueReusableCellWithIdentifier:@"TitleNewsCell"];
        
        [cell reloadDataCell:self.arrayContent[indexPath.row] andPublishTime:_publishTime AndHeignt:[self.arrayHeight[indexPath.row] floatValue]];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        return cell;
    }
    NSDictionary *dicContent =[self.arrayContent objectAtIndex:indexPath.row];
    if ([[dicContent objectForKey:@"type"] integerValue]==1) {
        NewsTitleCell *cell =[tableView dequeueReusableCellWithIdentifier:@"NewsTitleCell"];
        [cell reloadDataCell:dicContent AndHeignt:[self.arrayHeight[indexPath.row] floatValue]];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        return cell;
    }
    if ([[dicContent objectForKey:@"type"] integerValue]==2) {
        NewsImageCell *cell =[tableView dequeueReusableCellWithIdentifier:@"NewsImageCell"];
        [cell reloadDataCell:dicContent AndHeignt:[self.arrayHeight[indexPath.row] floatValue]];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        return cell;
    }
    if ([[dicContent objectForKey:@"type"] integerValue]==3) {
        NewsWebCell *cell =[tableView dequeueReusableCellWithIdentifier:@"NewsWebCell"];
        [cell reloadDataCell:dicContent AndHeignt:[self.arrayHeight[indexPath.row] floatValue]];
        
        __weak typeof(self)weakSelf =self;
        cell.block =^(float height){
            NSLog(@"%li",indexPath.row);
            NSString *strHeignt =[weakSelf.arrayHeight objectAtIndex:indexPath.row];
            if ([strHeignt floatValue]<10) {
                [weakSelf.arrayHeight replaceObjectAtIndex:indexPath.row withObject:[NSString stringWithFormat:@"%f",height]];
//                NSIndexPath *path = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
//                [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:path] withRowAnimation:UITableViewRowAnimationNone];
                [weakSelf.tableView reloadData];
            }
        };
        cell.clickBlock =^(NSString *url){
            ADDetailViewController *webVC =[[ADDetailViewController alloc] init];
            webVC.web_url =url;
            webVC.titleStr = @"资讯详情";
            [weakSelf.navigationController pushViewController:webVC animated:YES];
        };
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        return cell;
    }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dicContent =[self.arrayContent objectAtIndex:indexPath.row];
    if ([dicContent isKindOfClass:[NSDictionary class]]&&[[dicContent objectForKey:@"type"] integerValue]==2) {
        
        NSInteger index=0;
        for (NSInteger i=0; i<self.arrayImages.count; i++) {
            if ([[dicContent objectForKey:@"content"] isEqualToString:self.arrayImages[i]]) {
                index =i;
                break ;
            }
        }
//        NewsImageCell *cell = [tableView deselectRowAtIndexPath:indexPath animated:YES];
        UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
        NewsImageCell *imageCell = (NewsImageCell *)cell;
        [PhotoBrowser showBigPicWithImageUrls:self.arrayImages AndIndex:index AndFirstImageView:imageCell.imageNewsView];
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)getNewsDetailRequest {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:self.newsId,@"id", nil];
    [[CDAPIManager sharedManager] request_newsDetail_WithParams:dic andIsSign:YES andBlock:^(id data,NSError *error,BOOL isSuccess){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if (isSuccess) {
            
            NSDictionary *detailDic = [[data objectForKey:@"data"] objectForKey:@"detail"];
            _shareTitle = [detailDic objectForKey:@"title"];
            
            NSArray *arrayData =[[[data objectForKey:@"data"] objectForKey:@"detail"] objectForKey:@"content"];
            _publishTime = [[[data objectForKey:@"data"]objectForKey:@"detail"] objectForKey:@"publish_time"];
            [self.arrayContent addObject:[[[data objectForKey:@"data"]objectForKey:@"detail"] objectForKey:@"title"]];
            
            
            [self.arrayContent addObjectsFromArray:arrayData];
            self.arrayImages =[[data objectForKey:@"data"] objectForKey:@"images"];
            if ([NSString isEmpty:_shareImageStr]) {
                if (self.arrayImages.count>0) {
                    _shareImageStr = self.arrayImages[0];
                }
            }
            [self calculateCellHeight];
            self.labelNoData.hidden = YES;
            [self.tableView reloadData];
        }
        else
        {
            self.labelNoData.hidden = NO;
        }
    }];
}

- (void)calculateCellHeight {
    
    [self.arrayHeight removeAllObjects];
    for (NSInteger i=0; i<self.arrayContent.count; i++) {
        if (i==0) {
            float height =[NSString calculateTextHeight:DeviceWidth-30 Content:self.arrayContent[i] font:themeFont22];
            [self.arrayHeight addObject:[NSString stringWithFormat:@"%f",height+15+20+10+10]];//+20
            continue;
        }
        NSDictionary *dicContent =[self.arrayContent objectAtIndex:i];
        if ([[dicContent objectForKey:@"type"] integerValue]==1) {
            float height =[NSString calculateTextHeight:DeviceWidth-30 Content:[dicContent objectForKey:@"content"] font:themeBoldFont17];
            [self.arrayHeight addObject:[NSString stringWithFormat:@"%f",height+20.0]];
            continue;
        }
        if ([[dicContent objectForKey:@"type"] integerValue]==2) {
            float w,h;
            w =[[dicContent objectForKey:@"width"] floatValue];
            h =[[dicContent objectForKey:@"height"] floatValue];
            float imageWidth =[[dicContent objectForKey:@"width"] floatValue];
            float imageHeight =[[dicContent objectForKey:@"height"] floatValue];
            if (imageWidth>DeviceWidth -30) {
                w =DeviceWidth-30;
                h =(DeviceWidth -30)*imageHeight/imageWidth;
            }
            
            [self.arrayHeight addObject:[NSString stringWithFormat:@"%f",h+20]];
            continue;
        }
        if ([[dicContent objectForKey:@"type"] integerValue]==3) {
            [self.arrayHeight addObject:[NSString stringWithFormat:@"%f",0.0]];
            continue;
        }
    }

}

@end
